//
//  AppDelegate.swift
//  JKWeibo
//
//  Created by albert on 16/5/11.
//  Copyright © 2016年 albert. All rights reserved.
//

import UIKit

@UIApplicationMain

/*
command + shift + j 快速定位到目录
通过 ⬆️ ⬇️控制选中的目录
按下回车进入目录编辑模式
command + c 拷贝目录名称
command + n 新建文件夹
command + v 粘帖目录名称
下一步下一步 直到创建文件完毕
重复以上操作
*/
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?
    
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        // 1.创建window
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        
        // 2.设置根控制器
        //let mainVc = JKMainTabBarController()
        window?.rootViewController = defaultViewController()
        
        // 3.监听通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchRootViewController:", name: JKSwitchRootViewControllerNotification, object: nil)
        
        // 4.显示window
        window?.makeKeyAndVisible()
        
        // 5.连接打开数据库
        SQLiteManager.sharedInstance.openDB("status.sqlite")
        
        // 6.程序启动后，判断是否有缓存超过三天的数据，如果有，则删除
        JKStatusListModel.clearData()

        return true
    }
    
    // 移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }
    
    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }
    
    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }
    
    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }
    
    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
}

extension AppDelegate {
    
    //MARK: - 切换根控制器
    func switchRootViewController(noti: NSNotification){
        let str = noti.userInfo![JKSwitchRootViewControllerKey] as! String
        if str == JKSwitchToMainValue {
            window?.rootViewController = JKMainTabBarController()
            
        }else if str == JKSwitchToWelcomeValue{
            window?.rootViewController = R.storyboard.welcome.initialViewController!
        }
    }
    
    //MARK: - 返回默认根控制器
    private func defaultViewController() -> UIViewController{
        
        // 判断是否登录
        if JKUserAccount.isLogin() { // 已经登录
            
            // 判断是否是新版本
            if isNewVersion() { // 是新版本，返回新特性
                return R.storyboard.jKNewFeature.initialViewController!
                
            }else { // 不是新版本，返回主页
                return R.storyboard.welcome.initialViewController!
            }
        }
        
        // 未登录
        return JKMainTabBarController()
    }
    
    
    //MARK: - 判断是否有新版本
    /** 判断是否有新版本 */
    private func isNewVersion() -> Bool{
        
        // 1.获取Info.plist
        let dict = NSBundle.mainBundle().infoDictionary!
        
        // 2.获取当前版本号
        let currentVersion = dict["CFBundleShortVersionString"] as! String
        
        // 3.获取本地存储的版本号
        let defaults = NSUserDefaults.standardUserDefaults()
        let localVersion = (defaults.objectForKey("version") as? String) ?? "0.0"
        
        // 4.比较版本。还可以用compare比较升序降序
        if currentVersion != localVersion {
            JKLog("有新版本")
            
            // 存储新版本
            defaults.setObject(currentVersion, forKey: "version")
            
            return true
        }
        
        JKLog("没有新版本")
        return false
    }
}

/**
 打印LOG的弊端：
 1.非常消耗性能
 2.如果app部署到AppStoree之后，用户是看不到LOG的
 
 所以
 开发阶段：显示LOG
 部署阶段：隐藏LOG
 */

// 定义在类的大括号外面的函数就是全局函数，如果写在一个类大括号里面，就是这个类的函数，只能通过该类执行函数
// 函数的默认值：如果调用者没有传递对应的参数，那么系统就会使用默认值，如果调用者传递了参数，那么就会使用传入的参数
/**
由于编译器可以通过赋值的类型自动推导出数据的真实类型，所以在Swift开发中，能不写数据类型就不写数据类型
优点：可以减少冗余代码
*/
/**
泛型
如果想在函数中使用泛型，那么必须告诉系统这是一个泛型函数
注: 尖括号中可以随便填，但是一般就是写个T。表示泛型形参名的类型就是T类型，即传入什么类型就是什么类型
func 函数名<T>(泛型形参名: T) -> 返回值 {
}
*/
// T具体是什么类型由调用者决定，调用者传入什么类型，T就是什么类型
func JKLog<T>(message: T, fileName: String = __FILE__, methodName: String = __FUNCTION__, lineNumber: Int = __LINE__){
    
    #if DEBUG // Build Settings 搜索custom flag -> 给Debug添加一个自定义标记 -D DEBUG
        // 获得和QorumLogs一样的打印输出
        // AppDelegate.application(_:didFinishLaunchingWithOptions:).53:[;打印的内容
        //print("\((fileName as NSString).pathComponents.last!.componentsSeparatedByString(".").first!).\(methodName).\(lineNumber):\(message)")
        
        // 只需要函数名和行号就行了，没必要打印类名了，太长
        print("\(methodName).\(lineNumber):\(message)")
    #endif
}